<template>
  <div class="customer-service-container">
    <div class="chat-header">
      <h2>智能客服助手</h2>
      <div class="status-indicator" :class="{ 'connected': isConnected }">
        {{ isConnected ? '已连接' : '未连接' }}
      </div>
    </div>

    <div class="chat-messages" ref="messagesContainer">
      <div 
        v-for="message in messages" 
        :key="message.id"
        class="message"
        :class="message.role"
      >
        <div class="message-avatar">
          {{ message.role === 'user' ? '👤' : '🤖' }}
        </div>
        <div class="message-content">
          <div class="message-text">{{ message.content }}</div>
          <div class="message-time">{{ formatTime(message.timestamp) }}</div>
        </div>
      </div>
      
      <div v-if="isLoading" class="message assistant">
        <div class="message-avatar">🤖</div>
        <div class="message-content">
          <div class="loading-indicator">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
      </div>
    </div>

    <div class="chat-input">
      <el-input
        v-model="inputMessage"
        placeholder="请输入您的问题..."
        :disabled="!isConnected || isLoading"
        @keyup.enter="sendMessage"
        class="message-input"
      />
      <el-button 
        type="primary" 
        @click="sendMessage"
        :disabled="!inputMessage.trim() || !isConnected || isLoading"
        class="send-button"
      >
        发送
      </el-button>
    </div>

    <!-- 知识库管理面板 -->
    <el-drawer
      v-model="showKnowledgePanel"
      title="知识库管理"
      direction="rtl"
      size="400px"
    >
      <div class="knowledge-panel">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="添加知识" name="add">
            <el-form :model="newKnowledge" label-width="80px">
              <el-form-item label="标题">
                <el-input v-model="newKnowledge.title" placeholder="知识条目标题" />
              </el-form-item>
              <el-form-item label="内容">
                <el-input 
                  v-model="newKnowledge.content" 
                  type="textarea" 
                  :rows="4"
                  placeholder="知识条目内容"
                />
              </el-form-item>
              <el-form-item label="分类">
                <el-input v-model="newKnowledge.category" placeholder="知识分类" />
              </el-form-item>
              <el-form-item label="标签">
                <el-input v-model="newKnowledge.tags" placeholder="标签，用逗号分隔" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="addKnowledge" :loading="addingKnowledge">
                  添加知识
                </el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          
          <el-tab-pane label="知识库" name="list">
            <div class="knowledge-list">
              <div 
                v-for="item in knowledgeItems" 
                :key="item.id"
                class="knowledge-item"
              >
                <h4>{{ item.title }}</h4>
                <p>{{ item.content.substring(0, 100) }}...</p>
                <div class="knowledge-meta">
                  <span class="category">{{ item.category }}</span>
                  <span class="tags">{{ item.tags?.join(', ') }}</span>
                </div>
                <el-button 
                  size="small" 
                  type="danger" 
                  @click="deleteKnowledge(item.id)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="统计" name="stats">
            <div class="stats-info">
              <el-card>
                <template #header>知识库统计</template>
                <p>总条目数: {{ stats.totalItems }}</p>
                <p>已向量化: {{ stats.itemsWithEmbedding }}</p>
                <p>分类数量: {{ stats.categories.length }}</p>
                <p>标签数量: {{ stats.tags.length }}</p>
              </el-card>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-drawer>

    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button @click="showKnowledgePanel = true" icon="Document">
        知识库管理
      </el-button>
      <el-button @click="clearMessages" icon="Delete">
        清空对话
      </el-button>
      <el-button @click="testConnection" icon="Connection">
        测试连接
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { knowledgeBaseManager } from '../utils/knowledgeBase'
import { getAliyunConfig, validateAliyunConfig } from '../utils/aliyunConfig'
import type { KnowledgeItem } from '../utils/knowledgeBase'

// 响应式数据
const messages = ref<Array<{
  id: string
  role: 'user' | 'assistant'
  content: string
  timestamp: Date
}>>([])

const inputMessage = ref('')
const isLoading = ref(false)
const isConnected = ref(false)
const showKnowledgePanel = ref(false)
const activeTab = ref('add')
const messagesContainer = ref<HTMLElement>()

// 知识库相关
const knowledgeItems = ref<KnowledgeItem[]>([])
const addingKnowledge = ref(false)
const newKnowledge = reactive({
  title: '',
  content: '',
  category: '',
  tags: ''
})

const stats = reactive({
  totalItems: 0,
  itemsWithEmbedding: 0,
  categories: [] as string[],
  tags: [] as string[]
})

// 初始化
onMounted(async () => {
  await checkConnection()
  await loadKnowledgeItems()
  updateStats()
  
  // 添加欢迎消息
  addMessage('assistant', '您好！我是智能客服助手，有什么可以帮助您的吗？')
})

// 检查连接状态
const checkConnection = async () => {
  try {
    const config = getAliyunConfig()
    isConnected.value = validateAliyunConfig(config)
  } catch (error) {
    isConnected.value = false
    console.error('配置检查失败:', error)
  }
}

// 测试连接
const testConnection = async () => {
  try {
    isLoading.value = true
    const config = getAliyunConfig()
    
    if (!validateAliyunConfig(config)) {
      ElMessage.error('API配置不完整，请检查环境变量设置')
      return
    }
    
    // 测试简单的embedding生成
    const testEmbedding = await knowledgeBaseManager.search('测试', 1, 0.1)
    ElMessage.success('连接测试成功！')
    isConnected.value = true
  } catch (error) {
    ElMessage.error(`连接测试失败: ${error instanceof Error ? error.message : '未知错误'}`)
    isConnected.value = false
  } finally {
    isLoading.value = false
  }
}

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return
  
  const userMessage = inputMessage.value.trim()
  addMessage('user', userMessage)
  inputMessage.value = ''
  
  try {
    isLoading.value = true
    
    // 使用智能客服回复
    const reply = await knowledgeBaseManager.intelligentReply(
      userMessage,
      3, // 搜索前3个相关知识
      0.6, // 最小相似度阈值
      '你是一个专业的客服助手，请根据知识库内容回答用户问题。回答要简洁、准确、友好。如果知识库中没有相关信息，请礼貌地说明无法提供相关信息，并建议用户联系人工客服。'
    )
    
    addMessage('assistant', reply)
  } catch (error) {
    console.error('发送消息失败:', error)
    addMessage('assistant', '抱歉，我现在无法回答您的问题，请稍后再试。')
  } finally {
    isLoading.value = false
  }
}

// 添加消息
const addMessage = (role: 'user' | 'assistant', content: string) => {
  messages.value.push({
    id: Date.now().toString(),
    role,
    content,
    timestamp: new Date()
  })
  
  // 滚动到底部
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 清空消息
const clearMessages = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有对话记录吗？', '确认', {
      type: 'warning'
    })
    messages.value = []
    addMessage('assistant', '对话已清空，有什么可以帮助您的吗？')
  } catch {
    // 用户取消
  }
}

// 格式化时间
const formatTime = (date: Date) => {
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

// 加载知识库条目
const loadKnowledgeItems = async () => {
  try {
    knowledgeItems.value = knowledgeBaseManager.getAllItems()
  } catch (error) {
    console.error('加载知识库失败:', error)
  }
}

// 更新统计信息
const updateStats = () => {
  const statsData = knowledgeBaseManager.getStats()
  Object.assign(stats, statsData)
}

// 添加知识
const addKnowledge = async () => {
  if (!newKnowledge.title.trim() || !newKnowledge.content.trim()) {
    ElMessage.warning('请填写标题和内容')
    return
  }
  
  try {
    addingKnowledge.value = true
    
    const tags = newKnowledge.tags
      ? newKnowledge.tags.split(',').map(tag => tag.trim()).filter(Boolean)
      : []
    
    await knowledgeBaseManager.addItem({
      title: newKnowledge.title,
      content: newKnowledge.content,
      category: newKnowledge.category || undefined,
      tags: tags.length > 0 ? tags : undefined
    })
    
    // 清空表单
    newKnowledge.title = ''
    newKnowledge.content = ''
    newKnowledge.category = ''
    newKnowledge.tags = ''
    
    // 重新加载数据
    await loadKnowledgeItems()
    updateStats()
    
    ElMessage.success('知识添加成功！')
  } catch (error) {
    console.error('添加知识失败:', error)
    ElMessage.error('添加知识失败，请重试')
  } finally {
    addingKnowledge.value = false
  }
}

// 删除知识
const deleteKnowledge = async (id: string) => {
  try {
    await ElMessageBox.confirm('确定要删除这条知识吗？', '确认', {
      type: 'warning'
    })
    
    knowledgeBaseManager.deleteItem(id)
    await loadKnowledgeItems()
    updateStats()
    
    ElMessage.success('删除成功！')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除知识失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }
}

// 监听知识库变化
watch(knowledgeItems, () => {
  updateStats()
}, { deep: true })
</script>

<style scoped>
.customer-service-container {
  max-width: 800px;
  margin: 0 auto;
  height: 600px;
  display: flex;
  flex-direction: column;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fff;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
  background: #f5f7fa;
}

.chat-header h2 {
  margin: 0;
  color: #303133;
}

.status-indicator {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  background: #f56c6c;
  color: white;
}

.status-indicator.connected {
  background: #67c23a;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #fafafa;
}

.message {
  display: flex;
  margin-bottom: 16px;
  align-items: flex-start;
}

.message.user {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  margin: 0 12px;
  background: #e4e7ed;
}

.message-content {
  max-width: 70%;
  background: white;
  padding: 12px 16px;
  border-radius: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message.user .message-content {
  background: #409eff;
  color: white;
}

.message-text {
  margin-bottom: 4px;
  line-height: 1.5;
}

.message-time {
  font-size: 12px;
  color: #909399;
}

.message.user .message-time {
  color: rgba(255, 255, 255, 0.8);
}

.loading-indicator {
  display: flex;
  gap: 4px;
}

.loading-indicator span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #409eff;
  animation: loading 1.4s infinite ease-in-out;
}

.loading-indicator span:nth-child(1) { animation-delay: -0.32s; }
.loading-indicator span:nth-child(2) { animation-delay: -0.16s; }

@keyframes loading {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}

.chat-input {
  display: flex;
  padding: 16px 20px;
  border-top: 1px solid #e4e7ed;
  background: white;
}

.message-input {
  flex: 1;
  margin-right: 12px;
}

.send-button {
  min-width: 80px;
}

.toolbar {
  display: flex;
  gap: 8px;
  padding: 12px 20px;
  border-top: 1px solid #e4e7ed;
  background: #f5f7fa;
}

.knowledge-panel {
  padding: 20px;
}

.knowledge-list {
  max-height: 400px;
  overflow-y: auto;
}

.knowledge-item {
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  margin-bottom: 12px;
  background: #fafafa;
}

.knowledge-item h4 {
  margin: 0 0 8px 0;
  color: #303133;
}

.knowledge-item p {
  margin: 0 0 8px 0;
  color: #606266;
  font-size: 14px;
}

.knowledge-meta {
  display: flex;
  gap: 12px;
  margin-bottom: 8px;
  font-size: 12px;
}

.category {
  color: #409eff;
  background: rgba(64, 158, 255, 0.1);
  padding: 2px 6px;
  border-radius: 4px;
}

.tags {
  color: #909399;
}

.stats-info {
  padding: 20px 0;
}

.stats-info p {
  margin: 8px 0;
  color: #606266;
}
</style> 